package com.moorror.codegenvel.common.dialog;

import com.intellij.openapi.project.Project;
import com.moorror.codegenvel.common.table.bean.AbstractTableStringRow;
import com.moorror.codegenvel.common.tree.MTTreeCell;
import com.moorror.codegenvel.view.component.CommonHistoryTab;
import com.moorror.codegenvel.view.component.CodeGenByVelocityComponent;
import com.moorror.codegenvel.view.window.history.tree.MTTreeCellHistoryScene;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;

import javax.swing.*;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @Author jiyanghuang
 * @Date 2022/8/28 00:32
 */
public class DialogFormTreeHistory implements DialogFormMark {

    private Project project;

    private Consumer<List<? extends AbstractTableStringRow>> doUpdate;

    private String dialogTitle;

    private CommonHistoryTab commonHistoryTab;

    private Consumer<String> selectJson;

    /**
     *
     * @param project
     * @param dialogTitle
     */
    public DialogFormTreeHistory(Project project, String dialogTitle, String type, Consumer<String> selectJson) {
        this.project = project;
        this.dialogTitle = dialogTitle;
        this.selectJson = selectJson;
        commonHistoryTab = new CommonHistoryTab(project, type);
        CodeGenByVelocityComponent.getInstance(project).addTab(commonHistoryTab);

    }

    @Override
    public JComponent jComponent() {
        return commonHistoryTab;
    }

    @Override
    public String title() {
        if (StringUtils.isBlank(dialogTitle)) {
            return "Editor Table";
        }
        return dialogTitle;
    }

    @Override
    public Function<DialogFormTreeHistory, Pair<Boolean, String>> okFun() {
        return (form) -> {
//            doUpdate.accept(form.fetchText());
            // 树形表格无法新增等，因此只读原来对象就行
            MTTreeCell mtTreeCell = commonHistoryTab.currentSelect();
            if(null != mtTreeCell && mtTreeCell instanceof MTTreeCellHistoryScene){
                MTTreeCellHistoryScene cell = (MTTreeCellHistoryScene)mtTreeCell;
                if(null != selectJson){
                    cell.fetchViewValue();
                    selectJson.accept(cell.getPo().getExtColumnJson());
                }
            }
            return Pair.of(true, null);
        };
    }
}
